/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.pheromone;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.utc.ia04.antsontheweb.gui.request.AgentInterfaceRequest;
import org.utc.ia04.antsontheweb.utilities.PheromoneManagerMessage;
import org.utc.ia04.antsontheweb.utilities.Requete;
import org.utc.ia04.antsontheweb.utilities.RequeteException;

import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

public class PheromoneManagerReceiveBhv extends CyclicBehaviour
{
	//serialVersionUID
	private static final long serialVersionUID = -7854666979591427113L;

	public void action()
	{
		ACLMessage message = myAgent.receive();
		if(message == null)
			block();
		else
		{
			try
			{
				Requete r = Requete.deserialize_withException(message.getContent(), myAgent, message);
				
				switch(r.getType())
				{
					case Requete.ANT_UPDATEPHEROMONE :
						updatePheromoneTreatment(r.getContent(), message);
						break;
					case Requete.AC_ASKRESULT :
						askResutTreatment(r.getContent(), message);
						break;
					case Requete.ANTPARSER_ASKFORPHEROMONE :
						sendLinksWithPhTreatment(r.getContent(), message);
						break;
				}
			}
			catch (RequeteException e) { }	
		}
	}
	
	private void updatePheromoneTreatment(String content, ACLMessage message)
	{
		try
		{
			PheromoneManagerMessage r = PheromoneManagerMessage.deserialize_withException(content);
			((PheromoneManagerAgent)myAgent).getGraphic().insertNode(r.getCurrentUrl(), r.getNextUrl(), r.isCurrentTarget(), r.isNextTarget());
			((PheromoneManagerAgent)myAgent).getGraphic().incrementePheromone(r.getCurrentUrl());
			answer(message, null, ACLMessage.REQUEST, Requete.INC_TICK);
		}
		catch (RequeteException e)
			{ answer(message, PheromoneManagerAgent.UNFORMATTED, ACLMessage.FAILURE, Requete.PHEROMONE_ERROR); }
	}
	
	private void askResutTreatment(String content, ACLMessage message)
	{
		List<Node> nodes = ((PheromoneManagerAgent)myAgent).getGraphic().findNearestResourceProvider();
			
		//Send Answer to GUI
		ACLMessage answer = new ACLMessage(ACLMessage.REQUEST);
		Requete req = new Requete(Requete.PHEROMONEMANAGER_SENDPATHTOGUI, NetGraphic.getPathString(nodes).toString());
		answer.setContent(req.serialize());
		
		DFAgentDescription template = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType(AgentInterfaceRequest.DF_TYPE);
		template.addServices(sd);
		try
		{
			DFAgentDescription[] result = DFService.search(myAgent, template);
			for(int i = 0; i < result.length; ++i)
				answer.addReceiver(result[i].getName());
		}
		catch(Exception fe)
			{ System.out.println(fe.getMessage()); }
		
		myAgent.send(answer);
	}
	
	private void sendLinksWithPhTreatment(String content, ACLMessage message)
	{
		try
		{
			PheromoneManagerMessage msg = PheromoneManagerMessage.deserialize_withException(content);
			if(msg == null || msg.getSetOfUrl() == null)
				answer(message, PheromoneManagerAgent.UNFORMATTED, ACLMessage.FAILURE, Requete.PHEROMONE_ERROR);
			else
			{
				Set<URL> setOfUrl = msg.getSetOfUrl();
				
				HashMap<URL, Double> answer = ((PheromoneManagerAgent)myAgent).getGraphic().getLinksWithPheromone(setOfUrl);
				PheromoneManagerMessage pReq = new PheromoneManagerMessage(answer, null, null, null, null);
				answer(message, pReq.serialize(), ACLMessage.INFORM, Requete.PHEROMONEMANAGER_SENDLINKSWITHPH);
			}
		}
		catch(RequeteException e) { }
	}
	
	private void answer(ACLMessage message, String log, int performative, int typeRequete)
	{
		ACLMessage answer = message.createReply();
		message.setPerformative(performative);
		Requete r = new Requete(typeRequete, log);
		answer.setContent(r.serialize());
		myAgent.send(answer);
	}
}
